package com.huatai.auth.config;

import com.huatai.auth.constant.AuthCommonConstant;
import com.huatai.auth.service.HtUserDetails;
import com.huatai.auth.service.ThreadPoolService;
import com.huatai.common.util.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: ht-system
 * @description: 自定义扩展
 * @author: songxiude
 * @create: 2023-02-07 14:34
 **/
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
	@Autowired
	private JwtAccessTokenConverter jwtAccessTokenConverter;

	@Autowired
	private StringRedisTemplate redisTemplate;


	@Autowired
	private ThreadPoolService threadPoolService;

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
		HtUserDetails htUserDetails = (HtUserDetails) oAuth2Authentication.getUserAuthentication().getPrincipal();
		//token增加信息
		Map<String, Object> map = new HashMap<>();
		map.put("user_id", htUserDetails.getId());
		map.put("username", htUserDetails.getUsername());
		map.put("user_code", htUserDetails.getCode());
		map.put("name", htUserDetails.getName());
		map.put("real_name", htUserDetails.getRealName());
		map.put("avatar", htUserDetails.getAvatar());
		map.put("is_admin", htUserDetails.getIsAdmin());
		map.put("dept_id", htUserDetails.getDeptId());
		map.put("post_id", htUserDetails.getPostId());
		map.put("skin", htUserDetails.getSkin());
		((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(map);
		//存储信息到redis用于系统退出操作
		OAuth2AccessToken accessToken = jwtAccessTokenConverter.enhance(oAuth2AccessToken, oAuth2Authentication);
		//token
		String tokenValue = accessToken.getValue();
		//有效期
		int expiresIn = accessToken.getExpiresIn();
		//用户id
		String userid = Func.toStr(htUserDetails.getId());
		//保存redis
		redisTemplate.opsForValue().set(AuthCommonConstant.USER_TOKNE + ":" + userid, tokenValue, expiresIn, TimeUnit.SECONDS);
		//保存登录日志
		threadPoolService.saveLog(htUserDetails);
		return oAuth2AccessToken;
	}

}
